package com.handong.handserialprogram.module.singletask;

import android.text.TextUtils;
import android.util.Log;

import com.google.gson.Gson;
import com.handong.handserialprogram.constants.HttpConstant;
import com.handong.handserialprogram.model.CriminalModel;
import com.handong.handserialprogram.model.entities.CriminalEntity;
import com.handong.handserialprogram.model.entities.FootRingNewEntity;
import com.handong.handserialprogram.model.entities.LatLngEntity;
import com.handong.handserialprogram.model.status.EmergencyMsg;
import com.handong.handserialprogram.model.status.EmergencyResponse;
import com.handong.handserialprogram.model.status.MissionOverResponse;
import com.handong.handserialprogram.model.status.RingResponse;
import com.handong.handserialprogram.module.base.BasePresenter;
import com.handong.handserialprogram.module.base.BaseView;
import com.handong.handserialprogram.module.serialport.SerialPortUtil;
import com.handong.handserialprogram.utils.AppUtil;
import com.handong.handserialprogram.utils.AsyncHttpUtil;
import com.handong.handserialprogram.utils.EventBusUtil;
import com.handong.handserialprogram.utils.JLog;
import com.handong.handserialprogram.utils.SPUtil;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.TextHttpResponseHandler;

import org.apache.http.Header;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.Collections;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ExecutorService;

/**
 * Created by userKey on 2017/11/30.
 */

public class MissionPresenter extends BasePresenter<MissionActivity>{

    private static final String TAG = MissionPresenter.class.getSimpleName();
    private SerialPortUtil mSerialPortUtil;
    private List<CriminalEntity> mCriminalList;
    private CopyOnWriteArrayList<FootRingNewEntity> mList=new CopyOnWriteArrayList<FootRingNewEntity>();
    private CopyOnWriteArrayList<FootRingNewEntity> logoutFR;
    public String routeList;
    public String polygonList;
    public String startMarkerPoint;
    public String endMarkerPoint;
    //public int StopMissionSetDistance=3;

    private ExecutorService mWorkPool;



    public MissionPresenter(BaseView view) {
        super(view);
        init();
        logoutFR=new CopyOnWriteArrayList<>();
    }

    protected void init(){
        EventBusUtil.register(this);
        mSerialPortUtil = SerialPortUtil.getInstance(mView);
        mSerialPortUtil.openSerialPortToReadData();
        mSerialPortUtil.SetReadRunnableIsStop(true);
        mSerialPortUtil.updateWorking(true);
        setRemindSound(true);

        //发送IMEI

    }


    /**
     * 是否开启报警提示。
     */
    public void setRemindSound(boolean paramBoolean) {
        this.mSerialPortUtil.setPlaySound(paramBoolean);
    }
    protected boolean isBandingRing(int posstion){
       // return -1 != mIndex;
        FootRingNewEntity entity=mCriminalList.get(posstion).getRingEntity();
        if(entity!=null){
            return true;
        }
        return false;
    }
    protected boolean isBandingRings(){
        // return -1 != mIndex;
        if(mCriminalList==null){
            return false;
        }
        for (CriminalEntity entity:mCriminalList) {
            if(entity.getRingEntity()!=null){
                return true;
            }
        }
        return false;
    }

    protected boolean hasNotBandingRings(){
        for (CriminalEntity entity:mCriminalList) {
            if(entity.getRingEntity()==null){
                return true;
            }
        }
        return false;
    }
    protected boolean isNoBandingRings(){
        //boolean result=true;
        for (CriminalEntity entity:mCriminalList){
            if(entity.getRingEntity()!=null)
            {
                return false;
            }
        }
        return true;
    }



    protected void requestMissionDetail(final String missId){
        RequestParams params = new RequestParams("visit", "GetMain");
        params.put("MissId", missId);
        params.put("sys_companycode", SPUtil.getStringValue(SPUtil.LOGIN_CODE));
        AsyncHttpUtil.postSpecifiedRequest(mView, params, new TextHttpResponseHandler() {
            @Override
            public void onFailure(int i, org.apache.http.Header[] headers, String s, Throwable throwable) {
                JLog.d(TAG, s + "   |   " + throwable.toString());
                if (mView == null) {
                    return;
                }
                mView.loadMissionInfoFail(true);
            }
            @Override
            public void onSuccess(int i, org.apache.http.Header[] headers, String s) {
                JLog.d(TAG, s);
                if (mView == null) {
                    return;
                }
                if (TextUtils.isEmpty(s)) {
                    AppUtil.showShortToast(mView, "数据为空");
                    return;
                }
                Gson gson = new Gson();
                CriminalModel model = gson.fromJson(s, CriminalModel.class);
                if(model==null||model.getCriminal()==null){
                    mView.loadMissionInfoFail(false);
                    return;
                }

                mView.setCenterTitle(model.getTitle());
                routeList=model.getRoutePath();
                polygonList=model.getPolygonPath();
                LatLngEntity startAndStopLatLng=model.getLatLng();
                startMarkerPoint=startAndStopLatLng.getStartLat()+","+startAndStopLatLng.getStartLng();//new LatLng(startAndStopLatLng.getStartLat(),startAndStopLatLng.getStartLng());
                endMarkerPoint=startAndStopLatLng.getEndLat()+","+startAndStopLatLng.getEndLng();//new LatLng(startAndStopLatLng.getEndLat(),startAndStopLatLng.getEndLng());


                //获取线程安全的集合。
                mCriminalList = Collections.synchronizedList(model.getCriminal());
                //mLatLngEntity = model.getLatLng();
                if (mCriminalList == null || mCriminalList.isEmpty()){
                    mView.loadMissionInfoFail(false);
                    return;
                }
                boolean isHasBinding=false;
                mSerialPortUtil.mBindedRingList.clear();
                for(int j = 0;j<mCriminalList.size();j++){
                    if (!(mCriminalList.get(j).getEquipmentId()==null)){
                        isHasBinding=true;
                        mSerialPortUtil.mBindedRingList.add(mCriminalList.get(j).getEquipmentId());
                        FootRingNewEntity entity=new FootRingNewEntity();
                        entity.setRingID(mCriminalList.get(j).getEquipmentId());
                        mCriminalList.get(j).setRingEntity(entity);
                        entity.setWork(true);
                        entity.setIsActive(32);
                        //entity.setMyBingding(true);
                        mList.add(entity);

                        //mSendRunnable.setmRingList(logoutFR);
                    }
                }
                mSerialPortUtil.setRingList(mList);
                mSerialPortUtil.setSendStart();
                if (model.getState()==3)
                {
                    mView.changePause2Resume();
                }
                if(isHasBinding){
                    mSerialPortUtil.sendIMEI();
                }

                //显示犯人列表
                mView.showCriminalList(mCriminalList);
                mView.dealStartClick(mView.mMissionStatus);
            }
        });
    }

    /**
     * 判断当前是否有任何罪犯逃脱
     * @return
     */
    protected boolean checkIsAnyCriminalEscape()
    {
        for (FootRingNewEntity entity:
        logoutFR) {
            if (entity.isNormalWork()&&(entity.isNormalWork()&&(entity.isSignlarWeek()||SPUtil.getIntValue(SPUtil.STOP_MISSION_SET_DISTANCE)<=entity.getActualRingDistance()||!entity.isResponseDistance())))
            {
               return true;
            }
        }
        return false;
    }

//    protected void SendFirstCode()
//    {
//        if (!mBindedRingList.isEmpty()&&mSerialPortUtil!=null)
//        {
//            mSerialPortUtil.sendIMEI(mBindedRingList.get(0));
//        }
//
//    }

    /**
     * 通知服务端开始任务
     * @param missId
     */
    protected void requestStartMission(final String missId){
        RequestParams params = new RequestParams("visit", "StartMission");
        params.put("missId", missId);
        params.put("sys_companycode", SPUtil.getStringValue(SPUtil.LOGIN_CODE));
        AsyncHttpUtil.postSpecifiedRequest(mView, params, new TextHttpResponseHandler() {
            @Override
            public void onFailure(int i, org.apache.http.Header[] headers, String s, Throwable throwable) {
                JLog.d(TAG, s + "   |   " + throwable.toString());
                AppUtil.showShortToast(mView, "通知服务器开始任务失败");
            }
            @Override
            public void onSuccess(int i, org.apache.http.Header[] headers, String s) {

            }
        });
    }

    /**
     * 上传数据
     */
    protected void open2Server(String missionID){
        SPUtil.putStringValue(SPUtil.MISSION_ID, missionID);//保存任务ID
        mSerialPortUtil.openUploadThread();
        //mSerialPortUtil.startMission(missionID);
    }

    protected void queryMissionState(String missId) {
        if (!AsyncHttpUtil.isNetworkConnected(mView)) {
            return;
        }
        RequestParams params = new RequestParams("visit", "GetState");
        params.put("MissId", missId);
        mView.showLoadDialog("正在查询任务状态...");
        AsyncHttpUtil.postRequest(params, new TextHttpResponseHandler() {
            @Override
            public void onFailure(int i, Header[] headers, String s, Throwable throwable) {
                mView.dismissLoadingDialog();
                Log.d("服务器命令：","服务器无响应");
                AppUtil.showShortToast(mView, "服务器无响应");
            }

            @Override
            public void onSuccess(int i, Header[] headers, String s) {
                JLog.d("服务器命令1", "查询任务状态: " + s);
                if (TextUtils.isEmpty(s)) {
                    return;
                }
                try {
                    JSONObject object = new JSONObject(s);
                    if (!object.getBoolean("isClose")) {
                        stopMission();
                    } else {
                        requestStopMiss();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    mView.dismissLoadingDialog();
                    AppUtil.showShortToast(mView, "服务器无响应");
                }
            }
        });
    }

    /**
     * 暂停任务前确认是否已暂停
     */
    protected void queryMissionPauseState(String missId) {
        if (!AsyncHttpUtil.isNetworkConnected(mView)) {
            return;
        }
        RequestParams params = new RequestParams("visit", "GetState");
        params.put("MissId", missId);
        mView.showLoadDialog("正在查询任务状态...");
        AsyncHttpUtil.postRequest(params, new TextHttpResponseHandler() {
            @Override
            public void onFailure(int i, Header[] headers, String s, Throwable throwable) {
                mView.dismissLoadingDialog();
                AppUtil.showShortToast(mView, "服务器无响应");
            }

            @Override
            public void onSuccess(int i, Header[] headers, String s) {
                JLog.d("服务器命令2", "查询任务状态: " + s);
                if (TextUtils.isEmpty(s)) {
                    return;
                }
                try {
                    JSONObject object = new JSONObject(s);
                    if (!object.getBoolean("isPause")) {
                        mView.dismissLoadingDialog();
                        mView.changePause2Resume();
                        AppUtil.showShortToast(mView, "当前任务已经暂停");
                    } else {
                        requestPauseMiss();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    mView.dismissLoadingDialog();
                    AppUtil.showShortToast(mView, "服务器无响应");
                }
            }
        });
    }

    /**
     * 暂停任务前确认是否已恢复
     */
    protected void queryMissionResumeState(final String missId) {
        if (!AsyncHttpUtil.isNetworkConnected(mView)) {
            return;
        }
        RequestParams params = new RequestParams("visit", "GetState");
        params.put("MissId", missId);
        mView.showLoadDialog("正在查询任务状态...");
        AsyncHttpUtil.postRequest(params, new TextHttpResponseHandler() {
            @Override
            public void onFailure(int i, Header[] headers, String s, Throwable throwable) {
                mView.dismissLoadingDialog();
                AppUtil.showShortToast(mView, "服务器无响应");
            }

            @Override
            public void onSuccess(int i, Header[] headers, String s) {
                JLog.d("服务器命令3", "查询任务状态: " + s);
                if (TextUtils.isEmpty(s)) {
                    return;
                }
                try {
                    JSONObject object = new JSONObject(s);
                    if (!object.getBoolean("isResume")) {
                        mView.dismissLoadingDialog();
                        mView.changePause2Resume();
                        AppUtil.showShortToast(mView, "当前任务已经恢复");
                    } else {
                        updateMissionToResume(missId);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    mView.dismissLoadingDialog();
                    AppUtil.showShortToast(mView, "服务器无响应");
                }
            }
        });
    }

    /**
     * 暂停任务前确认是否已恢复
     */
    protected void updateMissionToResume(String missId) {
        if (!AsyncHttpUtil.isNetworkConnected(mView)) {
            return;
        }
        RequestParams params = new RequestParams("visit", "UpdateMissionState");
        params.put("id", missId);
        params.put("state","1");
        mView.showLoadDialog("正在修改任务状态...");
        AsyncHttpUtil.postRequest(params, new TextHttpResponseHandler() {
            @Override
            public void onFailure(int i, Header[] headers, String s, Throwable throwable) {
                mView.dismissLoadingDialog();
                AppUtil.showShortToast(mView, "服务器无响应");
            }

            @Override
            public void onSuccess(int i, Header[] headers, String s) {
                JLog.d(TAG, "修改任务状态: " + s);
                if (TextUtils.isEmpty(s)) {
                    return;
                }
                        mView.dismissLoadingDialog();
                        mView.changePause2Resume();
            }
        });
    }


    /**
     * 结束任务
     */
    public void stopMission() {
        mSerialPortUtil.closeUploadData();
        mView.stopMissionSuccess();
        logoutAllFootRing();
//        mView.showLoadDialog("正在休眠脚环...");
//
//        for (CriminalEntity entity:mCriminalList) {
//            if(entity.getRingEntity()!=null){
//                mSerialPortUtil.logoutFootRing(entity.getRingEntity().getRingID());
//            }
//        }

    }
//TODO 暂时修改
    protected void finishMiss2Server(){
        mSerialPortUtil.finishMiss2Server();
    }
    /**
     * 请求结束任务
     */
    protected void requestStopMiss() {
        mView.showLoadDialog("正在请求结束任务...");
        mSerialPortUtil.finishMiss2Server();
    }
    protected void requestPauseMiss() {
        mView.showLoadDialog("正在请求暂停任务...");
        mSerialPortUtil.pauseMiss2Server();
    }

    protected void requestResumeMiss() {
        mView.showLoadDialog("正在请求恢复任务...");
        mSerialPortUtil.resumeMiss2Server();
    }
    /**
     *休眠脚环
     */
//    protected void logoutFootRing(String ringID){
//        mSerialPortUtil.logoutFootRing(ringID);
//    }

    /**
     *休眠全部脚环
     */
    public void logoutAllFootRing() {
        Log.d("xxxx","size:"+logoutFR.size());
//        if(!logoutFR.isEmpty()&&mSerialPortUtil!=null){
//            String ringId=logoutFR.get(0).getRingID();
            this.mView.showLoadDialog("正在休眠脚环...");
            this.mSerialPortUtil.mSendRunnable.DelayTime=100;
            this.mSerialPortUtil.mSendRunnable.isLoginOut=true;
//        }
    }

    /**
     * 恢复当前第一个脚环
     */
    public void resumeCurrentFootRing(){
        if(!logoutFR.isEmpty()&&mSerialPortUtil!=null){
            String ringId=logoutFR.get(0).getRingID();
            //this.mView.showLoadDialog("正在休眠脚环："+ringId);
            this.mSerialPortUtil.resumeFootRing(ringId);
        }
    }

    //private boolean isRecovery=false;
    /**
     * 获取脚环数据
     */
    @Subscribe(priority = 100, threadMode = ThreadMode.MAIN)
    public void receiveFootRingList(CopyOnWriteArrayList<FootRingNewEntity> list) {
//        if ( mView == null || !mView.isResume()) {//mIndex == -1 ||
//            return;
//        }

        if ( mView == null ) {//mIndex == -1 ||
            return;
        }

        /**
         * 恢复脚环监听
         */
        if(mCriminalList!=null&&!mCriminalList.isEmpty()){
            for (CriminalEntity criminalEntity:mCriminalList) {
                for (FootRingNewEntity  footRingEntity:list) {
                    if(criminalEntity.getRingEntity()==null
                            &&criminalEntity.getEquipmentId()!=null
                            &&criminalEntity.getEquipmentId().equals(footRingEntity.getRingID())
                            &&footRingEntity.isMyBingding()){
                        criminalEntity.setRingEntity(footRingEntity);
                    }
                }
            }
        }


        logoutFR.clear();
        for (FootRingNewEntity entity:list) {
            if(entity.isMyBingding()){
                logoutFR.add(entity);
            }
        }
        //mSendRunnable.setmRingList(logoutFR);

        for (FootRingNewEntity footRingEntity:list) {
            for (int i=0;i<mCriminalList.size();i++){
                CriminalEntity entity= mCriminalList.get(i);
                if(entity.getRingEntity()!=null&&entity.getRingEntity().getRingID().equals(footRingEntity.getRingID())){
                    entity.setRingEntity(footRingEntity);
                    mView.refreshRingDistance(i);//更新item
                }
            }
        }
    }

    /**
     * 更新人员绑定设备
     * @param entity
     * @param missID
     */
    public void uploadBingRingInfo(final CriminalEntity entity, String missID) {

        RequestParams params = new RequestParams("visit", "UpdateBindEquipment");
        params.put("missId", missID);
        params.put("personId", entity.getPersonId());
        //todo 上传一对多时的脚环id 目前的一个，一对多时候改接口为多个
        if (!entity.getRingEntity().isDelete())
        {
            params.put("eId", entity.getRingEntity().getRingID());
        }
        else {
            params.put("eId", "");
        }

        params.put("code", SPUtil.getStringValue(SPUtil.LOGIN_CODE));

        AsyncHttpUtil.postRequest(params, new TextHttpResponseHandler() {
            @Override
            public void onFailure(int i, Header[] headers, String s, Throwable throwable) {
                mView.dismissLoadingDialog();
                mView.logoutFootRingError("服务器无响应");
                JLog.d(TAG, "Upload Result:" + throwable.toString());
            }

            @Override
            public void onSuccess(int i, Header[] headers, String s) {
                JLog.d(TAG, "Upload Result:" + s);
                if (!TextUtils.isEmpty(s.toString())) {
                    try {
                        JSONObject obj = new JSONObject(s);
                        if (obj.getBoolean(HttpConstant.RESPONSE_SUCCESS)) {
                            logoutFR.remove(entity.getRingEntity());
                            logoutAllFootRing();
                            //mSendRunnable.setmRingList(logoutFR);
                            if(logoutFR.isEmpty()){
                                mView.dismissLoadingDialog();
                                logoutSuccess();
                            }
                        } else {
                            mView.dismissLoadingDialog();
                            mView.logoutFootRingError(obj.getString(HttpConstant.FAIL_REASON));
                            //mView.bindPersonInfoFail(obj.getString(HttpConstant.FAIL_REASON));
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                        mView.dismissLoadingDialog();
                        mView.logoutFootRingError("服务器无响应");

                    }
                } else {
                    mView.dismissLoadingDialog();
                    mView.logoutFootRingError("服务器无响应");
                }
            }
        });
    }

//    public void updateDelay(int delayTime)
//    {
//        mSerialPortUtil.mSendRunnable.DelayTime=delayTime;
//    }

    @Subscribe(priority = 100, threadMode = ThreadMode.MAIN)
    public void receiveRingResponse(RingResponse response) {
        if (!isBandingRings()) {
            return;
        }
        switch (response.getResponseCode()) {
            case RingResponse.LOGOUT_ORDER://休眠脚环
                if (response.isSuccess()) {
//                    if(!logoutFR.isEmpty()){
//                        FootRingNewEntity result=FootRingNewUtil.findFootRingById(logoutFR,response.getRingID());
//                        if (result!=null) {
//                            if (result.isDelete()) {
//                                for (CriminalEntity entity :
//                                        mCriminalList) {
//                                    if (entity.getRingEntity() == result) {
//                                        uploadBingRingInfo(entity, mView.mMissionID);
//                                    }
//                                }
//
//
//                            } else {
//                                //synchronized (logoutFR) {
//                                    logoutFR.remove(result);
//                                    //result.setDelete(true);
//                                    //mSendRunnable.setmRingList(logoutFR);
//                                    logoutAllFootRing();
//
//                                    if (logoutFR.isEmpty()) {
//                                        mView.dismissLoadingDialog();
//                                        logoutSuccess();
//                                    }
//                               // }
//                            }
//                        }
                    mView.dismissLoadingDialog();
                    Log.d("注销命令","注销成功");
                    logoutSuccess();
//                        break;
//                    }else{
//                        mView.dismissLoadingDialog();
//                        logoutSuccess();
//                    }
                } else {
//                    for (FootRingNewEntity entity :
//                            logoutFR) {
//                        entity.setDelete(false);
//                    }
                    //mSendRunnable.setmRingList(logoutFR);
                    mView.dismissLoadingDialog();
                    mView.logoutFootRingError(response.getRingID());
                    Log.d("注销命令","注销失败："+response.getRingID());
                }

                break;

            case RingResponse.SIM_ERROR:
                if (mView.isMissionExecuting()) {
                    mView.simInitErrorMissOpen(response.getRingID());
                    return;
                }
//                mView.simInitError(response.getRingID());
                break;
            default:
                return;
        }
    }

    /**
     * 设置是否上传暂停
     * @param isPause
     */
    protected void setIsUploadPause(boolean isPause)
    {
        mSerialPortUtil.setIsUploadPause(isPause);
    }

    /**
     * 强制退出
     */
    protected void logoutSuccess(){
        for (CriminalEntity criminalEntity:mCriminalList) {
            criminalEntity.setRingEntity(null);
        }
        if (mSerialPortUtil!=null) {
            mSerialPortUtil.closeSerialPort();
        }
        mSerialPortUtil = null;
        mView.isForceFinish=true;
        mView.finishRefreshDistance();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void receiveEmergencyResult(EmergencyResponse response) {
        if (mView == null || !mView.isResume()){
            return;
        }
        mView.dealEmergencyResponse(response);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void receiveEmergencyMsg(EmergencyMsg msg) {
        if (mView == null || !mView.isResume()){
            return;
        }
        if (msg.isStart()) {
            mView.sendEmergencyRequest();
        } else {
            mView.askUserForEmergency();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN, priority = 80)
    public void receiveMissionOver(MissionOverResponse response) {
        mView.dismissLoadingDialog();
        Log.d("服务器命令：",response.toString());
        switch (response.getOrder()) {
            case MissionOverResponse.OVER_SUCCESS:// 服务器结束任务成功
                    mSerialPortUtil.destroyFinishThread();
                    mView.showResponseSuccessDialog();

                break;

            case MissionOverResponse.OVER_TIME_OUT://服务器任务结束连接超时
                mView.showFinMissTimeOutDialog();
                //mSerialPortUtil.closeAlert2Server();//到时间清除弹框
                break;

            case MissionOverResponse.OVER_REJECT:// 服务器不允许结束任务
                mView.showServerRejectDialog();
                mSerialPortUtil.destroyFinishThread();// TODO 注意这里结束了线程可能不对。
                break;

            case MissionOverResponse.OVER_ERROR://请求结束任务错误
                mView.showSendErrorDialog();
                break;

            case MissionOverResponse.OVER_RESPONSE://请求发出

                mView.showLoadDialog("请求已发送，等待指挥中心回复...");
                break;

            case MissionOverResponse.SERVER_REQUEST:// 服务器请求结束任务
                mView.showMissionOverDialog();

                break;
            case MissionOverResponse.SERVER_RESUME_MISSION:
                mView.updateMissionState();
                break;
            case MissionOverResponse.UPDATE_ROUTE:
                polygonList=response.getMessage();
                break;
        }
    }

    /**
     * 退出
     * @return  false 不可以退出 true 可以退出
     */
    protected boolean stopExit(){
        if (mView != null && mView.isMissionExecuting()){
        //if (mView != null ){
            AppUtil.showShortToast(mView, "结束任务后，才能退出");
            return false;
        }
        if ((this.mCriminalList == null) || (this.mCriminalList.isEmpty())) {
            return true;
        }

        if(isBandingRings()){
            for (FootRingNewEntity entity:
                 logoutFR) {
                entity.setDelete(true);
            }
            //mSendRunnable.setmRingList(logoutFR);
            mView.showExitDialog();
            return  false;
        }

        return true;
    }

    protected void pauseUploadData() {
        mSerialPortUtil.closeUploadData();
    }


    protected void resumeUploadData() {
        mSerialPortUtil.openUploadThread();
    }

    /**
     * 通过用户校验密码校验身份 暂时
     * @param password
     * @return
     */
    public boolean checkPassword(String password) {
        if (password.equals(SPUtil.getStringValue(SPUtil.USER_PASSWORD, "123456")))
            return true;
        else return false;
    }

    @Override
    protected void exit() {
        EventBusUtil.unRegister(this);
        AsyncHttpUtil.cancelSpecifiedRequest(mView);
        if (this.mSerialPortUtil != null) {
            this.mSerialPortUtil.closeUploadData();
            this.mSerialPortUtil.closeSerialPort();
        }
        SPUtil.remove(SPUtil.MISSION_ID);
        super.exit();
    }
}
